package cn.tedu.straw.redis.tag.controller;

import cn.tedu.straw.commons.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;

@RestController
@RequestMapping("/portal/tag")
public class TagController {

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    // http://localhost:8300/portal/tag
    @GetMapping("")
    public R<List<Serializable>> getTagList() {
        // 通过RedisTemplate获取列表类型的“操作器”
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        // 标签列表数据在Redis中的Key
        String tagsKey = "tags";
        // 从Redis中读取标签列表
        long start = 0;
        long end = ops.size(tagsKey);
        List<Serializable> tags = ops.range(tagsKey, start, end);
        // 响应
        return R.ok(tags);
    }

    //http://localhost:8300/portal/tag/13
    //http://localhost/redis-tag/portal/tag/13
    @GetMapping("/{id}")
    public Serializable getTag(@PathVariable("id") Integer id){
        ValueOperations<String,Serializable> valueOps=redisTemplate.opsForValue();
        Serializable tag= valueOps.get("tag"+id);
        return tag;
    }

}
